package com.zpark.user_system.servlet;

import com.zpark.user_system.utils.JDBCUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Arrays;

/**
 * @PackageName: com.zpark.user_system.servlet
 * @ClassName: UpdateUserInfoServlet
 * @Description:
 * @author: RZS
 * @date: 2023/3/21  16:01
 */
@WebServlet("/user/update.do")
public class UpdateUserInfoServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1、获取需要修改的用户信息
        Integer id = Integer.parseInt(request.getParameter("id"));
        String password = request.getParameter("password");
        String sex = request.getParameter("sex");
        String languages = Arrays.toString(request.getParameterValues("language"));
        String city = request.getParameter("city");

        // 定义数据库连接对象信息
        Connection conn = null;
        PreparedStatement stat = null;

        try {
            // 获取数据库连接对象
            conn = JDBCUtils.getConnection();
            // 开启事务
            conn.setAutoCommit(false);
            // 编写sql
            String sql = "update user set password = ?, sex = ?, language = ?, city = ? where id = ?";
            // 获取预编译对象
            stat = conn.prepareStatement(sql);
            // 替换占位符
            stat.setString(1, password);
            stat.setString(2, sex);
            stat.setString(3, languages);
            stat.setString(4, city);
            stat.setInt(5, id);
            // 执行sql
            stat.executeUpdate();

            // 提交事务
            conn.commit();

            // 修改完成之后返回查看用户列表页面
            request.getRequestDispatcher("/user/find_user_all.do").forward(request, response);
        } catch(Exception e) {
            // 事务回滚
            try {
                conn.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        }finally {
            // 关闭数据库连接
            JDBCUtils.close(conn, stat, null);
        }

    }
}
